package org.finesys.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.finesys.common.constants.CacheConstants;
import org.finesys.common.mp.core.service.impl.BaseServiceImpl;
import org.finesys.system.api.entity.SysRoleMenu;
import org.finesys.system.api.vo.RoleVO;
import org.finesys.system.mapper.SysRoleMenuMapper;
import org.finesys.system.service.SysRoleMenuService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysRoleMenuServiceImpl extends BaseServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService {

    /**
     * 根据 roleId 删除对应的菜单信息
     */
    @Override
    @CacheEvict(value = CacheConstants.MENU_DETAILS, key = "#roleId")
    public void deleteRoleMenuByRoleId(Long roleId) {
        baseMapper.delete(Wrappers.<SysRoleMenu>update().lambda().eq(SysRoleMenu::getRoleId, roleId));
    }

    @Override
    @Caching(evict = {
            @CacheEvict(value = CacheConstants.MENU_DETAILS, key = "#roleVO.roleId"),
            @CacheEvict(value = CacheConstants.USER_DETAILS, allEntries = true)
    })
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveRoleMenus(RoleVO roleVO) {
        //删除
        deleteRoleMenuByRoleId(roleVO.getRoleId());
        //存入数据
        if (StringUtils.isEmpty(roleVO.getMenuIds())) {
            return Boolean.TRUE;
        }
        List<SysRoleMenu> roleMenuList = Arrays.stream(roleVO.getMenuIds().split(StrUtil.COMMA)).map(menuId -> {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setMenuId(Long.valueOf(menuId));
            sysRoleMenu.setRoleId(roleVO.getRoleId());
            return sysRoleMenu;
        }).collect(Collectors.toList());
        this.saveBatch(roleMenuList);
        return Boolean.TRUE;
    }
}
